import React, { Component } from "react";
import { connect } from "react-redux";
import {
  asyncDelUserById,
  asyncAddUserItem,
  asyncInitUserList,
} from "../action/deluseraction";
import userModel from "../model/useraxios";
import { deluser, inituserlist, adduser } from "../action/deluseraction";
import store from "../store";
class AsyncUser extends Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      username: "",
      userpwd: "",
    };
  }
  async componentDidMount() {
    let { data: list } = await userModel.query({});
    store.dispatch(inituserlist(list));
  }

  add = async () => {
    //新增的方法

    await userModel.add({
      name: this.state.username,
      pwd: this.state.userpwd,
    });
    let { data: list } = await userModel.query({});

    store.dispatch(inituserlist(list));
  };
  del = async (id: any) => {
    await userModel.del(id);
    store.dispatch(deluser(id));
  };

  render() {
    return (
      <div>
        User
        <hr></hr>
        <div>
          <div>
            用户名{" "}
            <input
              type="text"
              value={this.state.username}
              onChange={(e) => {
                this.setState({
                  username: e.target.value,
                });
              }}
            />
          </div>

          <div>
            密码{" "}
            <input
              type="text"
              value={this.state.userpwd}
              onChange={(e) => {
                this.setState({
                  userpwd: e.target.value,
                });
              }}
            />
          </div>
          <button
            onClick={() => {
              this.add();
            }}
          >
            新增
          </button>
        </div>
        <div className="table">
          <div className="tr">
            <div className="td">编号</div>
            <div className="td">用户名</div>
            <div className="td">密码</div>
            <div className="td">操作</div>
          </div>
          {this.props.list.map((item: any) => {
            return (
              <div className="tr" key={item.id}>
                <div className="td">{item.id}</div>
                <div className="td">{item.name}</div>
                <div className="td">{item.pwd}</div>
                <div
                  className="td"
                  onClick={() => {
                    this.del(item.id);
                  }}
                >
                  删除
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}
let mapDispatchToProps = {
  asyncAddUserItem,
  asyncDelUserById,
  asyncInitUserList,
};
let mapStateToProps = (state: any) => ({
  list: state.user.list,
});
export default connect(mapStateToProps, mapDispatchToProps)(AsyncUser);
